package com.gang.easyexcel_demo.controller;

import com.alibaba.excel.EasyExcel;
import com.gang.easyexcel_demo.ExcelService;
import com.gang.easyexcel_demo.dao.DemoDAO;
import com.gang.easyexcel_demo.entity.Student;
import com.gang.easyexcel_demo.listener.DemoDataListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@RestController
public class EasyExcelDemo {

    @Autowired
    private DemoDAO demoDAO;
    @Autowired
    private ExcelService excelService;

    public List<Student> getData() {
        List<Student> list = new ArrayList<>();
        Student s1 = new Student(1, "张三", "123123123");
        Student s2 = new Student(2, "李四", "123123123");
        Student s3 = new Student(3, "王五", "123123123");
        list.add(s1);
        list.add(s2);
        list.add(s3);
        return list;
    }

    @GetMapping("download")
    public void download(HttpServletResponse response) throws IOException {
        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), Student.class).sheet("模板").doWrite(getData());
    }

    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file) throws IOException {

        List<Student> list = excelService.readExcel(file);
        System.out.println(list);

        EasyExcel.read(file.getInputStream(), Student.class, new DemoDataListener(demoDAO)).sheet("模板").doRead();

        return "success";
    }

}
